<?php
/**
 * Created by PhpStorm.
 * User: wodrow
 * Date: 4/11/17
 * Time: 2:07 PM
 */

namespace common\models;

use common\components\big_data\BaiRong;
use yii\base\ErrorException;

/**
 * Class CreditOrder
 * @package common\models
 *
 * @property Custom $custom
 * @property CreditOrderLog[] $creditOrderLogs
 * @property Bank $bank
 * @property GuaranteeCompanyDotSite $guaranteeCompanyDotSite
 * @property BankGuaranteeCompanyBind $bankGuaranteeCompanyBind
 * @property BaiRongValidateForCreditOrder[] $baiRongValidateForCreditOrders
 * @property BaiRongValidateLog[] $baiRongValidateLogs
 * @property BaiRongValidateLog $baiRongValidateLogDetailList
 * @property BaiRongValidateLog $baiRongValidateLogPersonRecognition
 */
class CreditOrder extends \common\models\base\CreditOrder
{
	const STATUS_DEFAULT = 10;
	const STATUS_HAS_SEND = 11;
	const STATUS_HAS_GAIN = 12;
	const STATUS_HAS_UPDATE = 13;
	const BIG_DATA_VALIDATE_STATUS_DEFAULT = 10;
	const BIG_DATA_VALIDATE_STATUS_REJECT = 11;
	const BIG_DATA_VALIDATE_STATUS_REVIEW = 12;
	const BIG_DATA_VALIDATE_STATUS_ACCEPT = 15;
    const RELATION_SELF = '本人';
    const RELATION_POUSE = '配偶';
    const RELATION_GUARANTEE = '担保人';
    const IDTYPE_IDCARD = '000'; // 身份证

	public static function getStatus()
    {
        return [
            self::STATUS_DEFAULT => '默认',
            self::STATUS_HAS_SEND => '已发送',
            self::STATUS_HAS_GAIN => '已获取',
            self::STATUS_HAS_UPDATE => '已更新',
        ];
    }

    public static function getRelationType()
    {
        return [
            self::RELATION_SELF => self::RELATION_SELF,
            self::RELATION_POUSE => self::RELATION_POUSE,
            self::RELATION_GUARANTEE => self::RELATION_GUARANTEE,
        ];
    }

    public static function getIdtype()
    {
        return [
            self::IDTYPE_IDCARD => '身份证',
        ];
    }

    public function attributeLabels()
    {
        return [
            'id' => 'ID',
            'custom_id' => '客户id',
            'custname' => '征信人',
            'idtype' => '证件类型',
            'idno' => '证件号',
            'relation' => '关系',
            'bank_id' => 'Bank ID',
            'guarantee_company_dot_site_id' => 'Guarantee Company Dot Site ID',
            'status' => 'Status',
            'serialize_data' => 'Serialize Data',
        ];
    }

    public function baiRongValidate()
    {
        $bair_comp_conf = $this->guaranteeCompanyDotSite->link_bairong_component_conf;
        /**
         * @var BaiRong $bairong
         */
        $bairong = \Yii::$app->$bair_comp_conf;
        $data = $bairong->check($this->custname, $this->idno, $this->mobile);
        foreach ($data['validate_log'] as $k => $v){
            $m = BaiRongValidateForCreditOrder::findOne(['credit_order_id' => $this->id, 'bai_rong_validate_log_id' => $v['id']]);
            if (!$m){
                $m = new BaiRongValidateForCreditOrder();
                $m->credit_order_id = $this->id;
                $m->bai_rong_validate_log_id = $v['id'];
                $m->created_at = time();
                if (!$m->save()){
                    throw new ErrorException("bai_rong_validate_for_credit_log保存失败");
                }
            }
        }
    }

    /**
     * @return array
     */
    public function getBairongResult()
    {
        /**
         * @var BaiRongValidateLog[] $logs
         */
        $logs = $this->baiRongValidateLogs;
        $bairong_conf = $this->guaranteeCompanyDotSite->link_bairong_component_conf;
        /**
         * @var BaiRong $br
         */
        $br = \Yii::$app->$bairong_conf;
        $str = '';
        foreach ($logs as $k => $v) {
            if ($v->strategy_type == BaiRongValidateLog::STRATEGY_TYPE_DETAIL_LIST){
                $str .= $br->formatDetailList($v['resp_data_for_api_send']);
            }
            if ($v->strategy_type == BaiRongValidateLog::STRATEGY_TYPE_PERSON_RECOGNITION){
                if ($v->is_old_from_console){
                    $str .= $br->formatPersionRecognitionOld($v['resp_data_for_api_send']);
                }else{
                    $str .= $br->formatPersionRecognition($v['resp_data_for_api_send']);
                }
            }
        }
        $url = [];
        $swift_numbers = [];
        foreach ($logs as $k => $v) {
            $swift_number = $v->resp_swift_number;
            $login_data = $br->getWebLoginData();
            $token = $login_data['tokenid'];
            $url[$v->strategy_type] = $br->selectStrategy($br->need_strategys[$v->strategy_type])['report_url_pre']."{$swift_number}/{$token}";
            $swift_numbers[$v->strategy_type] = $swift_number;
        }
        $r = [];
        $r['optimize_show'] = $br->optimizeShowStr($str);
        $r['url'] = $url;
        $r['swift_numbers'] = $swift_numbers;
        return $r;
    }

	/**
	 * @return \yii\db\ActiveQuery
	 */
	public function getCustom()
	{
		return $this->hasOne(Custom::className(), ['id'=>'custom_id']);
	}
	
	/**
	 * @return \yii\db\ActiveQuery
	 */
	public function getBank()
	{
		return $this->hasOne(Bank::className(), ['id'=>'bank_id']);
	}
	
	/**
	 * @return \yii\db\ActiveQuery
	 */
	public function getGuaranteeCompanyDotSite()
	{
		return $this->hasOne(GuaranteeCompanyDotSite::className(), ['id'=>'guarantee_company_dot_site_id']);
	}
	
	/**
	 * @return \yii\db\ActiveQuery
	 */
	public function getCreditOrderLogs()
	{
		return $this->hasMany(CreditOrderLog::className(), ['credit_order_id' => 'id']);
	}
	
	/**
	 * @return BankGuaranteeCompanyBind $model
	 */
	public function getBankGuaranteeCompanyBind()
	{
		$model = BankGuaranteeCompanyBind::findOne(['bank_id'=>$this->bank->id, 'guarantee_company_id'=>$this->guaranteeCompanyDotSite->guaranteeCompany->id]);
		return $model;
	}

    /**
     * @return \yii\db\ActiveQuery
     */
    public function getBaiRongValidateForCreditOrders()
    {
        return $this->hasMany(BaiRongValidateForCreditOrder::className(), ['credit_order_id' => 'id']);
    }

    /**
     * @return \yii\db\ActiveQuery
     */
    public function getBaiRongValidateLogs()
    {
        return $this->hasMany(BaiRongValidateLog::className(), ['id' => 'bai_rong_validate_log_id'])->viaTable('{{%bai_rong_validate_for_credit_order}}', ['credit_order_id' => 'id']);
    }

    /**
     * @return BaiRongValidateLog|null
     */
    public function getBaiRongValidateLogDetailList()
    {
//        return $this->hasOne(BaiRongValidateLog::className(), ['id' => 'bai_rong_validate_log_id', 'staregy_type' => BaiRongValidateLog::STRATEGY_TYPE_DETAIL_LIST])->viaTable('{{%bai_rong_validate_for_credit_order}}', ['credit_order_id' => 'id']);
        $x = null;
        foreach ($this->baiRongValidateLogs as $k => $v){
            if ($v->strategy_type == BaiRongValidateLog::STRATEGY_TYPE_DETAIL_LIST){
                $x = $v;
            }
        }
        return $x;
    }

    /**
     * @return BaiRongValidateLog|null
     */
    public function getBaiRongValidateLogPersonRecognition()
    {
        $x = null;
        foreach ($this->baiRongValidateLogs as $k => $v){
            if ($v->strategy_type == BaiRongValidateLog::STRATEGY_TYPE_PERSON_RECOGNITION){
                $x = $v;
            }
        }
        return $x;
    }
}